package com.fone.player.activity.personal;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.Formatter;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fone.player.R;
import com.fone.player.activity.BaseActivity;
import com.fone.player.activity.personal.adapter.CollectionListAdatper;
import com.fone.player.activity.personal.adapter.CollectionManageListAdatper;
import com.fone.player.bean.RecordData;
import com.fone.player.client.Callback;
import com.fone.player.client.CollectionRst;
import com.fone.player.client.CollectionlsRst;
import com.fone.player.client.Error;
import com.fone.player.client.Request;
import com.fone.player.constant.FoneConstant;
import com.fone.player.entity.OfflineCache;
import com.fone.player.play.FonePlayerActivity;
import com.fone.player.play.PlayerAction;
import com.fone.player.play.PlayerFrom;
import com.fone.player.sns.UserInfoManager;
import com.fone.player.storage.SharedPreferenceModule;
import com.fone.player.storage.StorageModule;
import com.fone.player.storage.download.DownloadUtil;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.util.SystemUtil;
import com.fone.player.view.ChangeTempLimitDialog;
import com.fone.player.widget.xlistview.XListView;
import com.fone.player.widget.xlistview.XListView.IXListViewListener;

/**
 * 网络收藏具体模块,包含网络收藏的管理设置页面
 * 
 * 
 * @author JasonZue
 * @since 2014-4-21
 */
@SuppressLint("HandlerLeak")
public class NetCollectionActivity extends BaseActivity implements
		IXListViewListener, OnScrollListener, OnClickListener,
		OnItemClickListener {

	private static final String TAG = "NetCollectionActivity";

	private TextView mTitleTv;
	private Button mLeftBt, mRightBt;
	private XListView mCollectionListView;
	private CollectionListAdatper mCollectionListAdatper;
	private CollectionManageListAdatper mManageListAdatper;

	private List<OfflineCache> collectionData = new ArrayList<OfflineCache>(); // 收藏及收藏管理界面使用的数据
																				// 新
	private List<RecordData> mCollectionDeleteData = new ArrayList<RecordData>();// 删除收藏同步使用的数据

	private Context mContext;
	private Handler mHandler;

	private RelativeLayout storageInfoRl, mNoDataRl, mAutoCheckBoxRl;
	private RelativeLayout mWaitingRl;
	private LinearLayout deleteLl, mLoginLl;
	private CheckBox autoDownloadCb;
	@SuppressWarnings("unused")
	private ProgressBar mStoragePb;
	@SuppressWarnings("unused")
	private TextView mAvailableTv, mDownloadTextTv, mLoginTv;
	private EditText mLimitET;

	private Button deleteBt, selectAll;

	public static boolean isAutoDownload = false;
	public static final int NORMAL_MODE = 1; // 普通界面模式
	public static final int MANAGEMENT_MODE = 2;// 管理界面模式
	public static final int TV_SERISE_MODE = 3;// 电视剧界面模式
	public static final int TV_SERISE_MODE_BY_ITEM = 4;// 电视剧界面模式(从勾选跳转)

	public static final int CACHEWHILEPLAY = 7;// 边下边播
	public static final int ADD_TO_CACHE = 8;// 添加到下载列表
	public static final int DELETE_FROM_CACHE = 9;// 下载列表删除
	public static final int UPDATE_LIMIT_TEMP_TEXT = 10;// 更新限制大小
	public int ViewMode = NORMAL_MODE;
	private boolean isSelectedAllbt = false;

	// private SharedPreferences mSp;
	private long baseItem;
	private int count;// 记录勾选数量
	private CollectionCallback callback;
	private ChangeCollectionCallback changeCollectionCallback;
	private boolean requestedFlag = false;
	private int requestPage = 1;// 请求页数
	@SuppressWarnings("unused")
	private boolean isShowEventData = false; // 标识符 用于再次进入页面时,过滤上一次的eventbus数据
	private boolean isMounted;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.personal_collection_view);
		mContext = getApplicationContext();
		initHandler();
		initView();
		initData();
		// getAvailableStorage();
		isMounted = SystemUtil.getInstance().isSDCardMounted();
		resetCollectionNewCount();

	}

	/**
	 * 初始化handler
	 * 
	 * @return void
	 * @throws
	 */
	private void initHandler() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);

				switch (msg.what) {
				case UPDATE_LIMIT_TEMP_TEXT:
					// 更新临时文件限制大小
					String text = SharedPreferenceModule.getInstance()
							.getString(
									FoneConstant.TMP_LIMIT_ITEM_LONG_FLAG_SP,
									Formatter.formatFileSize(mContext,
											baseItem * 1));
					mLimitET.setText(text);

					break;

				default:
					break;
				}
			}
		};
	}

	/**
	 * 初始化数据
	 */
	private void initData() {

		// loginedFlag = UserInfoManager.isLogin() == true ? true : false;

		baseItem = isMounted == true ? (SystemUtil.getInstance()
				.getTotalSpaceByteBySDCard() / 8) : (SystemUtil.getInstance()
				.getTotalSpaceByteByPhoneBody() / 8);

		// 从sp中获取存入的限制上限 并设置对应文字

		switch (SharedPreferenceModule.getInstance().getInt(
				FoneConstant.TMP_LIMIT_CHOOSED_ID_FLAG_SP, R.id.rt_limit_item1)) {
		case R.id.rt_limit_item1:
			mLimitET.setText(SharedPreferenceModule.getInstance().getString(
					FoneConstant.TMP_LIMIT_ITEM_LONG_FLAG_SP,
					Formatter.formatFileSize(mContext, baseItem * 1)));
			SharedPreferenceModule.getInstance().setLong(
					FoneConstant.TMP_LIMIT_SIZE, baseItem * 1);

			break;
		case R.id.rt_limit_item2:
			mLimitET.setText(SharedPreferenceModule.getInstance().getString(
					FoneConstant.TMP_LIMIT_ITEM_LONG_FLAG_SP,
					Formatter.formatFileSize(mContext, baseItem * 2)));
			SharedPreferenceModule.getInstance().setLong(
					FoneConstant.TMP_LIMIT_SIZE, baseItem * 2);
			break;
		case R.id.rt_limit_item3:
			mLimitET.setText(SharedPreferenceModule.getInstance().getString(
					FoneConstant.TMP_LIMIT_ITEM_LONG_FLAG_SP,
					Formatter.formatFileSize(mContext, baseItem * 3)));
			SharedPreferenceModule.getInstance().setLong(
					FoneConstant.TMP_LIMIT_SIZE, baseItem * 3);
			break;
		case R.id.rt_limit_item4:
			mLimitET.setText(SharedPreferenceModule.getInstance().getString(
					FoneConstant.TMP_LIMIT_ITEM_LONG_FLAG_SP,
					Formatter.formatFileSize(mContext, baseItem * 4)));
			SharedPreferenceModule.getInstance().setLong(
					FoneConstant.TMP_LIMIT_SIZE, baseItem * 4);
			break;
		}
		// 设置登录入口显示
		isShowingLoginLL();

		// 网络请求 取回收藏信息
		callback = new CollectionCallback();
		changeCollectionCallback = new ChangeCollectionCallback();

	}

	/**
	 * 获取收藏列表数据 登录时同步未更新数据并获取最新列表 未登录时 从数据库中取出收藏列表
	 * 
	 * @return void
	 * @throws
	 */
	private void getCollectionData(int requestPage) {

		// 从数据库获取未成功同步的内容 封装data数据 发送请求
		List<RecordData> updateInfo = new ArrayList<RecordData>();

		if (UserInfoManager.isLogin()) {
			// 获取数据库中未同步的数据
			ArrayList<OfflineCache> unsynchronized = StorageModule
					.getInstance().getFavouriteList(
							OfflineCache.CACHE_FAVOURITE_SYNCHRONZIE_ALL_WAIT);
			L.v("JasonZue", "未同步的数据:" + unsynchronized.toString());
			for (int i = unsynchronized.size(); i > 0; i--) {
				// ++改--因为顺序问题
				RecordData recordData = new RecordData();
				recordData.ccid = unsynchronized.get(i - 1).getCacheCCID();
				recordData.cid = unsynchronized.get(i - 1).getCacheCID();
				recordData.videoid = unsynchronized.get(i - 1)
						.getCacheVideoId();
				recordData.clid = unsynchronized.get(i - 1).getCacheCLID();
				recordData.type = unsynchronized.get(i - 1)
						.getCacheSynchronzieType();
				recordData.ifp = unsynchronized.get(i - 1).getCacheReportPage();
				L.v("JasonZue", "我的视频页,收藏同步数据上报页面:"
						+ unsynchronized.get(i - 1).getCacheReportPage());
				recordData.updatetime = unsynchronized.get(i - 1)
						.getCacheCreateTime();
				updateInfo.add(recordData);
				L.v("JasonZue",
						"我的收藏-->同步数据上传的videoId:"
								+ unsynchronized.get(i - 1).getCacheVideoId()
								+ " 同步数据上传的时间:"
								+ unsynchronized.get(i - 1)
										.getCacheCreateTime());
			}

			if (FoneUtil.isNetOkWithToast(mContext)) {
				// if (!requestedFlag) {
				if (updateInfo.size() < 1) {
					Request.getInstance().collectionls(requestPage, 1, null,
							callback);
				} else {
					Request.getInstance().collectionls(requestPage, 1,
							updateInfo, callback);
				}
				// }
			}
			mWaitingRl.setVisibility(View.VISIBLE);
		} else {
			// 从数据库中获取列表
			collectionData.clear();
			collectionData.addAll(StorageModule.getInstance()
					.mergeFavouriteDownloadStateByVideoId(
							StorageModule.getInstance().getFavouriteList()));
			if (collectionData.size() > 0) {
				mCollectionListAdatper.notifyDataSetChanged();
				mWaitingRl.setVisibility(View.GONE);
				mNoDataRl.setVisibility(View.GONE);
				mRightBt.setVisibility(View.VISIBLE);
			} else {
				mNoDataRl.setVisibility(View.VISIBLE);
				mRightBt.setVisibility(View.GONE);
			}

		}

	}

	private void initView() {
		mLeftBt = (Button) findViewById(R.id.common_title_left_bt);
		mRightBt = (Button) findViewById(R.id.common_title_right_bt);
		mTitleTv = (TextView) findViewById(R.id.common_title_text_tv);

		mLeftBt.setText(mContext.getResources().getString(
				R.string.collection_title_text));
		mRightBt.setText(mContext.getResources().getString(
				R.string.collection_title_right_delete_text));
		mTitleTv.setVisibility(View.GONE);
		mRightBt.setVisibility(View.GONE);

		deleteBt = (Button) findViewById(R.id.collection_delete_bt);
		selectAll = (Button) findViewById(R.id.collection_select_all_bt);

		mStoragePb = (ProgressBar) findViewById(R.id.collection_avalible_storage_pb);
		mAvailableTv = (TextView) findViewById(R.id.collection_useable_storage_text);
		mLimitET = (EditText) findViewById(R.id.collection_storage_limit_et);
		mDownloadTextTv = (TextView) findViewById(R.id.collection_auto_download_text_tv);
		mLoginTv = (TextView) findViewById(R.id.collection_login_text);

		mLimitET.setOnClickListener(this);
		mLeftBt.setOnClickListener(this);
		mRightBt.setOnClickListener(this);
		mLoginTv.setOnClickListener(this);

		// 1)自动缓存开关 用SP记录数据 2)根据记录的数据设置标志位 isAutoDownload(默认false 关闭)
		autoDownloadCb = (CheckBox) findViewById(R.id.collection_auto_download_cb);
		isAutoDownload = SharedPreferenceModule.getInstance().getBoolean(
				FoneConstant.AUTO_DOWNLOAD_FLAG_SP, true);
		autoDownloadCb.setChecked(isAutoDownload);

		storageInfoRl = (RelativeLayout) findViewById(R.id.collection_storage_login_rl);
		mNoDataRl = (RelativeLayout) findViewById(R.id.collection_no_data_rl);
		deleteLl = (LinearLayout) findViewById(R.id.collection_delete_ll);
		mLoginLl = (LinearLayout) findViewById(R.id.collection_login_rl);
		mAutoCheckBoxRl = (RelativeLayout) findViewById(R.id.collcetion_auto_download_switch_rl);
		mWaitingRl = (RelativeLayout) findViewById(R.id.collection_waiting_rl);
		mAutoCheckBoxRl.setVisibility(View.GONE);
		mCollectionListView = (XListView) findViewById(R.id.collection_lv);
		// 收藏普通adapter
		mCollectionListAdatper = new CollectionListAdatper(mContext,
				collectionData, mHandler, NORMAL_MODE);
		// 收藏管理adapter
		mManageListAdatper = new CollectionManageListAdatper(mContext,
				collectionData);

		mCollectionListView.setAdapter(mCollectionListAdatper);

		mCollectionListView.setPullRefreshEnable(false);
		mCollectionListView.setPullLoadEnable(false);
		mCollectionListView.setEnableDragLoadMore(false);
		mCollectionListView.setXListViewListener(this);
		mCollectionListView.setOnScrollListener(this);

		autoDownloadCb
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {

						SharedPreferenceModule.getInstance().setBoolean(
								FoneConstant.AUTO_DOWNLOAD_FLAG_SP, isChecked);
						if (!isChecked) {
							FoneUtil.showToast(
									mContext,
									R.string.cache_wifi_download_only_close_text);
							// startAllCache();
						} else {
							FoneUtil.showToast(mContext,
									R.string.cache_wifi_download_only_open_text);
							if (StorageModule.MSG_WIFI_NETWORK_TYPE != DownloadUtil
									.getNetType()) {
								// 如果当前不是WIFI网络,暂停所有缓存内容
								StorageModule.getInstance().pauseAllCache(true);
							}
						}
					}
				});

		mCollectionListView.setOnItemClickListener(this);
		deleteBt.setOnClickListener(this);
		selectAll.setOnClickListener(this);

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

	}

	@Override
	public void onRefresh() {

	}

	@Override
	public void onLoadMore() {

		getCollectionData(requestPage);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK && ViewMode == MANAGEMENT_MODE) {
			change2Normal();
			// 清空删除数据
			for (int i = 0; i < collectionData.size(); i++) {
				collectionData.get(i).setCacheIsDelete(false);
				collectionData.get(i).setCacheSynchronzieType(
						OfflineCache.CACHE_FAVOURITE_SYNCHRONZIE_ADD_ALREADY);
			}
			isSelectedAllbt = false;
			return true;
		}
		if (keyCode == KeyEvent.KEYCODE_BACK && ViewMode == TV_SERISE_MODE) {
			change2Normal();
			return true;
		}

		return super.onKeyDown(keyCode, event);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.common_title_right_bt:
			// 顶部右按钮
			switch (ViewMode) {
			case NORMAL_MODE:
				if (FoneUtil.isNetOkWithToast(mContext)) {
					change2Manage();
				}
				break;
			case MANAGEMENT_MODE:
				change2Normal();
				// 清除选中数据
				if (collectionData.size() == count) {
					selectAll.setText(mContext.getResources().getString(
							R.string.collection_cancel_all_text));
					isSelectedAllbt = true;
				} else {
					selectAll.setText(mContext.getResources().getString(
							R.string.collection_select_all_text));
					isSelectedAllbt = !isSelectedAllbt;
				}
				for (int i = 0; i < collectionData.size(); i++) {
					collectionData.get(i).setCacheIsDelete(false);
					collectionData
							.get(i)
							.setCacheSynchronzieType(
									OfflineCache.CACHE_FAVOURITE_SYNCHRONZIE_ADD_ALREADY);
				}
				break;
			}
			break;
		case R.id.collection_delete_bt:
			// 移除的时候不可以用++ 否则数据会污染
			if (FoneUtil.isNetOkWithToast(mContext)) {
				// 无网不允许删除操作
				doDelete();
			}
			break;

		case R.id.collection_select_all_bt:
			// 修改所有bean中deleteSelected数据
			changeDeleteSelected();
			break;

		case R.id.common_title_left_bt:
			// 点击返回同物理返回键处理逻辑一致
			if (ViewMode == MANAGEMENT_MODE) {
				change2Normal();
				// 清除选中数据
				for (int i = 0; i < collectionData.size(); i++) {
					collectionData.get(i).setCacheIsDelete(false);
					collectionData
							.get(i)
							.setCacheSynchronzieType(
									OfflineCache.CACHE_FAVOURITE_SYNCHRONZIE_ADD_ALREADY);
				}
			} else if (ViewMode == TV_SERISE_MODE) {
				change2Normal();
			} else if (ViewMode == NORMAL_MODE) {
				finish();
			}
			break;

		case R.id.collection_login_text:
			// 点击登录跳转
			FoneUtil.toLoginPage(this, "7");
			break;
		case R.id.collection_storage_limit_et:
			// 弹出空间选择框
			new ChangeTempLimitDialog(mContext, this, mHandler);
			break;

		default:
			break;
		}
	}

	/**
	 * 执行收藏删除操作(删除选中条目)
	 * 
	 * @return void
	 * @throws
	 */
	private void doDelete() {

		// 修改全选按钮文字
		selectAll.setText(mContext.getResources().getString(
				R.string.collection_select_all_text));

		// 更新当前数据到数据库中
		StorageModule.getInstance().updateFavouriteSynchronzieType(
				collectionData);

		// checkLocalDB("执行收藏删除后的数据库:");
		List<OfflineCache> deleteCacheList = new ArrayList<OfflineCache>();
		for (int i = collectionData.size(); i > 0; i--) {
			if (collectionData.get(i - 1).getCacheIsDelete()) {
				RecordData recordData = new RecordData();
				recordData.ccid = collectionData.get(i - 1).getCacheCCID();
				recordData.cid = collectionData.get(i - 1).getCacheCID();
				recordData.clid = collectionData.get(i - 1).getCacheCLID();
				recordData.videoid = collectionData.get(i - 1)
						.getCacheVideoId();
				recordData.type = collectionData.get(i - 1)
						.getCacheSynchronzieType();// 待删除记录

				OfflineCache offlineDeleteCache = new OfflineCache();
				offlineDeleteCache = collectionData.get(i - 1);

				collectionData.remove(i - 1);
				mCollectionDeleteData.add(recordData);
				deleteCacheList.add(offlineDeleteCache);

			}
		}
		mManageListAdatper.notifyDataSetChanged();

		if (UserInfoManager.isLogin()) {
			// 向服务器同步删除数据
			L.v("JasonZue", "向服务器同步删除数据" + mCollectionDeleteData.toString()
					+ "     collectionDataNew:" + collectionData.toString());

			changeCollectionCallback.setDeleteCacheList(deleteCacheList);
			if (FoneUtil.isNetOkWithToast(mContext)
					&& deleteCacheList.size() > 0) {
				Request.getInstance().collection(mCollectionDeleteData, 2, 1,
						0, 0, changeCollectionCallback);
				mWaitingRl.setVisibility(View.VISIBLE);
			}
		} else {
			// 未登录情况下清除本地数据库中对应数据
			L.v("JasonZue", "删除的list:" + deleteCacheList.toString());
			StorageModule.getInstance().deleteFavourite(deleteCacheList);
		}
		// 清空请求中使用的数据
		mCollectionDeleteData.clear();

		if (deleteCacheList.size() > 0) {
			FoneUtil.showToast(mContext, R.string.cache_delete_success_text);
		} else {
			FoneUtil.showToast(mContext, R.string.cache_no_seleted_video_text);
		}
		deleteBt.setText(mContext.getResources().getString(
				R.string.collection_title_right_delete_text));
		deleteBt.setTextColor(mContext.getResources().getColor(
				R.color.btn_unpress_text_color));

		// 判断是否还有可以显示的数据
		if (collectionData.size() < 1) {
			mNoDataRl.setVisibility(View.VISIBLE);
			mCollectionListView.setVisibility(View.GONE);
		}

	}

	/**
	 * 修改全选 删除选中状态
	 * 
	 * @return void
	 * @throws
	 */
	private void changeDeleteSelected() {

		if (collectionData.size() > 0) {

			for (int i = 0; i < collectionData.size(); i++) {
				if (!isSelectedAllbt) {
					collectionData.get(i).setCacheIsDelete(true);
					collectionData
							.get(i)
							.setCacheSynchronzieType(
									OfflineCache.CACHE_FAVOURITE_SYNCHRONZIE_DELETE_WAIT);
				} else {
					collectionData.get(i).setCacheIsDelete(false);
					collectionData
							.get(i)
							.setCacheSynchronzieType(
									OfflineCache.CACHE_FAVOURITE_SYNCHRONZIE_ADD_ALREADY);
				}
			}
			isSelectedAllbt = !isSelectedAllbt;
			if (isSelectedAllbt) {
				selectAll.setText(mContext.getResources().getString(
						R.string.collection_cancel_all_text));
				deleteBt.setText("删除(" + collectionData.size() + ")");
				deleteBt.setTextColor(mContext.getResources().getColor(
						R.color.btn_pressed_text_color));
			} else {
				selectAll.setText(mContext.getResources().getString(
						R.string.collection_select_all_text));
				deleteBt.setText(mContext.getResources().getString(
						R.string.collection_title_right_delete_text));
				deleteBt.setTextColor(mContext.getResources().getColor(
						R.color.btn_unpress_text_color));
			}
			mManageListAdatper.notifyDataSetChanged();
		} else {
			FoneUtil.showToast(mContext,
					R.string.collection_have_no_added_collection_text);
		}
	}

	/**
	 * 判断是否显示登录条
	 * 
	 * @return void
	 * @throws
	 */
	private void isShowingLoginLL() {
		if (UserInfoManager.isLogin()) {
			mLoginLl.setVisibility(View.GONE);
		} else {
			mLoginLl.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 切换到管理视图
	 * 
	 * @return void
	 * @throws
	 */
	private void change2Manage() {
		ViewMode = MANAGEMENT_MODE;
		deleteLl.setVisibility(View.VISIBLE);
		storageInfoRl.setVisibility(View.GONE);
		mDownloadTextTv.setText("请勾选需要删除的收藏条目");
		autoDownloadCb.setVisibility(View.GONE);
		mRightBt.setVisibility(View.VISIBLE);
		mRightBt.setText(mContext.getResources().getString(
				R.string.collection_title_right_cancel_text));
		mLeftBt.setText(mContext.getResources().getString(
				R.string.collection_title_text));
		deleteBt.setText(mContext.getResources().getString(
				R.string.collection_title_right_delete_text));
		selectAll.setText(mContext.getResources().getString(
				R.string.collection_select_all_text));
		deleteBt.setTextColor(mContext.getResources().getColor(
				R.color.btn_unpress_text_color));
		mCollectionListView.setAdapter(mManageListAdatper);
		isShowingLoginLL();
	}

	/**
	 * 切换到普通视图
	 * 
	 * @return void
	 * @throws
	 */
	private void change2Normal() {
		ViewMode = NORMAL_MODE;
		deleteLl.setVisibility(View.GONE);
		storageInfoRl.setVisibility(View.VISIBLE);
		mDownloadTextTv.setText("wifi环境下自动下载勾选内容");
		autoDownloadCb.setVisibility(View.VISIBLE);
		mRightBt.setText(mContext.getResources().getString(
				R.string.collection_title_right_delete_text));
		if (collectionData.size() > 0) {
			mRightBt.setVisibility(View.VISIBLE);
		} else {
			mRightBt.setVisibility(View.GONE);
		}
		mLeftBt.setText(mContext.getResources().getString(
				R.string.collection_title_text));
		mCollectionListView.setAdapter(mCollectionListAdatper);
		isShowingLoginLL();
		// getAvailableStorage();// 更新容量大小
	}

	private class CollectionCallback implements Callback<CollectionlsRst> {

		@Override
		public void onSuccess(CollectionlsRst t) {
			L.v("JasonZue", "CollectionCallback onSuccess ",
					"收藏bean:" + t.toString());
			mWaitingRl.setVisibility(View.GONE);
			if (t.result == 0) {
				requestedFlag = true;
				if ("0".equals(t.total)) {
					// 收藏总数为0,提示用户没有收藏内容
					mNoDataRl.setVisibility(View.VISIBLE);
					mRightBt.setVisibility(View.GONE);
					mCollectionListView.setVisibility(View.GONE);
				} else {
					mNoDataRl.setVisibility(View.GONE);
					mRightBt.setVisibility(View.VISIBLE);
					mCollectionListView.setVisibility(View.VISIBLE);
					// 获取cnt列表数据
					if (null == t.cnts) {
						L.e(TAG, "CollectionCallback onSuccess",
								"收藏数据错误 cnts==null");
						return;
					}
					if (null != t.cnts.cntList) {
						for (int i = 0; i < t.cnts.cntList.size(); i++) {
							OfflineCache itemBean = new OfflineCache();
							itemBean.setCacheContentType(t.cnts.cntList.get(i).type);
							// FIXME 类型转换可能出错(溢出)
							itemBean.setSortIndex((int) t.cnts.cntList.get(i).udate);
							itemBean.setCacheName(t.cnts.cntList.get(i).name);
							itemBean.setCacheDetailUrl(t.cnts.cntList.get(i).durl);
							itemBean.setCacheXYZPlayUrl(t.cnts.cntList.get(i).url);
							itemBean.setCacheEpisodeNum(t.cnts.cntList.get(i).season);
							itemBean.setCacheImageUrl(t.shost
									+ FoneUtil.formatUrl(t.cnts.cntList.get(i).pic));
							itemBean.setCacheEpisodeUpdateInfo(t.cnts.cntList
									.get(i).updateinfo);
							itemBean.setCacheDownloadState(OfflineCache.CACHE_STATE_NOT_DOWNLOAD);
							itemBean.setCacheIsDelete(false);
							itemBean.setCacheIsDownlaod(false);
							itemBean.setCacheSynchronzieType(0);
							itemBean.setCacheIsVip(t.cnts.cntList.get(i).vip == 1 ? true
									: false);
							itemBean.setCacheIsDownloadable(t.cnts.cntList
									.get(i).btndown == 0 ? false : true);
							formatIDS(itemBean, t.cnts.cntList.get(i).rurl);
							if (t.cnts.cntList.get(i).type == 2
									|| t.cnts.cntList.get(i).type == 3
									|| t.cnts.cntList.get(i).type == 4) {
								itemBean.setCacheDramaUrl(t.cnts.cntList.get(i).durl);
							} else {
								itemBean.setCacheDramaUrl(null);
							}
							collectionData.add(itemBean);
						}
						// 同步收藏列表到数据库并合并内容
						L.v("JasonZue",
								"添加数据库前的数据:" + collectionData.toString());
						StorageModule.getInstance().addFavouriteList(
								collectionData);

						// 请求合并缓存存在状态数据
						StorageModule.getInstance()
								.mergeFavouriteDownloadStateByVideoId(
										collectionData);
						if (null != t.rp) {
							if (t.rp.p < t.rp.m) {
								mCollectionListView.setEnableDragLoadMore(true);
								mCollectionListView.setPullLoadEnable(true);
								if (requestPage + 1 <= t.rp.m) {
									requestPage = requestPage + 1;
								}
							} else {
								mCollectionListView
										.setEnableDragLoadMore(false);
								mCollectionListView.setPullLoadEnable(false);
							}
						}

						mCollectionListAdatper.notifyDataSetChanged();
						changeSynchroizeStatus2Already();
					}
				}
			} else {
				mNoDataRl.setVisibility(View.VISIBLE);
				mCollectionListView.setVisibility(View.GONE);
				FoneUtil.showToast(mContext,
						R.string.collection_cannot_get_data_text);
				requestedFlag = false;
			}
		}

		@Override
		public void onFailure(Error error) {
			L.v(TAG, "CollectionCallback onFailure", "isNetworkError : "
					+ error.isNetworkError() + " status : " + error.getStatus()
					+ " reason : " + error.getReason());
			FoneUtil.showToast(mContext,
					R.string.collection_cannot_get_data_text);
			// 切换界面
			mNoDataRl.setVisibility(View.VISIBLE);
			mCollectionListView.setVisibility(View.GONE);
			mWaitingRl.setVisibility(View.GONE);
		}
	}

	/**
	 * 删除数据请求回调
	 * */
	private class ChangeCollectionCallback implements Callback<CollectionRst> {

		private List<OfflineCache> deleteCacheList;

		public void setDeleteCacheList(List<OfflineCache> deleteCacheList) {

			this.deleteCacheList = deleteCacheList;
		}

		@Override
		public void onSuccess(CollectionRst t) {
			L.v("JasonZue", "onSuccess:删除收藏结果" + t.toString());
			// 清空数据库中对应记录
			StorageModule.getInstance().deleteFavourite(deleteCacheList);
			mWaitingRl.setVisibility(View.GONE);
		}

		@Override
		public void onFailure(Error error) {
			L.v(TAG, "AddCollectionCallback onFailure", "isNetworkError : "
					+ error.isNetworkError() + " status : " + error.getStatus()
					+ " reason : " + error.getReason());
			FoneUtil.showToast(mContext,
					R.string.collection_fail_to_delete_cloud_data_text);
			mWaitingRl.setVisibility(View.GONE);
		}

	}

	/**
	 * 将同步后的文件状态记录为已同步
	 * 
	 * @return void
	 * @throws
	 */
	private void changeSynchroizeStatus2Already() {
		ArrayList<OfflineCache> unsynchronized = StorageModule.getInstance()
				.getFavouriteList(
						OfflineCache.CACHE_FAVOURITE_SYNCHRONZIE_ALL_WAIT);
		for (int i = 0; i < unsynchronized.size(); i++) {
			unsynchronized.get(i).setCacheSynchronzieType(
					OfflineCache.CACHE_FAVOURITE_SYNCHRONZIE_ADD_ALREADY);
		}
		StorageModule.getInstance().updateFavouriteSynchronzieType(
				unsynchronized);
	}

	/**
	 * 根据传入的url 截取cid ccid videoid clid
	 * 
	 * @param itemBean
	 * @return CacheItemBean
	 * @throws
	 */
	public static void formatIDS(OfflineCache itemBean, String rurl) {
		String cid = "";
		String ccid = "";
		String videoid = "";
		String clid = "";
		L.v(TAG,
				"formatIDS",
				"name=" + itemBean.getCacheName()
						+ itemBean.getCacheEpisodeNum() + " rurl=" + rurl);
		String stringlist[] = rurl.substring(rurl.indexOf("?") + 1).split("&");
		for (int i = 0; i < stringlist.length; i++) {
			if (stringlist[i].startsWith("cid=")) {
				cid = stringlist[i].substring(stringlist[i].indexOf("=") + 1);
			}
			if (stringlist[i].startsWith("ccid=")) {
				ccid = stringlist[i].substring(stringlist[i].indexOf("=") + 1);
			}
			if (stringlist[i].startsWith("videoid=")) {
				videoid = stringlist[i]
						.substring(stringlist[i].indexOf("=") + 1);
			}
			if (stringlist[i].startsWith("clid=")) {
				clid = stringlist[i].substring(stringlist[i].indexOf("=") + 1);
			}
		}
		// L.v("JasonZue", "截取结果" + " cid:" + cid + " ccid:" + ccid +
		// " videoid:"
		// + videoid + " clid:" + clid);

		itemBean.setCacheCCID(Integer.valueOf(ccid));
		itemBean.setCacheCID(Integer.valueOf(cid));
		itemBean.setCacheVideoId(Integer.valueOf(videoid));
		itemBean.setCacheCLID(Integer.valueOf(clid));
	}

	@Override
	protected void onResume() {
		super.onResume();
		mCollectionListView.setEnableDragLoadMore(false);
		mCollectionListView.setPullLoadEnable(false);
		if (UserInfoManager.isLogin()) {
			requestedFlag = false;
			requestPage = 1;
		}
		if (requestedFlag) {
			StorageModule.getInstance().mergeFavouriteDownloadStateByVideoId(
					collectionData);
			mCollectionListAdatper.notifyDataSetChanged();
			mManageListAdatper.notifyDataSetChanged();
			return;
		} else {
			if (ViewMode == NORMAL_MODE) {
				// 未登陆-->登录 重新请求同步数据
				mNoDataRl.setVisibility(View.GONE);
				collectionData.clear();
				mCollectionListAdatper.notifyDataSetChanged();
				getCollectionData(requestPage);

			}
			isShowingLoginLL();
			if (ViewMode == MANAGEMENT_MODE) {
				// 注掉 fix 2740
				// collectionData.clear();
				// mManageListAdatper.notifyDataSetChanged();
				// getCollectionData();
			}
			StorageModule.getInstance().mergeFavouriteDownloadStateByVideoId(
					collectionData);
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		// EventBus.getDefault().unregister(this);
	}

	@Override
	protected void onStop() {
		super.onStop();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (FoneUtil.isNetOkWithToast(mContext)) {

			CheckBox mBox = (CheckBox) view
					.findViewById(R.id.cache_is_selected_cb);

			try {
				switch (ViewMode) {
				case NORMAL_MODE:
					// 普通模式

					// 根据类型执行跳转操作
					switch (collectionData.get(position - 1)
							.getCacheContentType()) {
					case OfflineCache.CACHE_CONTENT_TYPE_TV:
					case OfflineCache.CACHE_CONTENT_TYPE_VARIETY:
					case OfflineCache.CACHE_CONTENT_TYPE_ANIMATION:
						// 剧集类的跳转事件
						Intent intent = new Intent(mContext,
								FonePlayerActivity.class);

						intent.putExtra("from", PlayerFrom.COLLECTION_LIST);
						intent.putExtra("action", PlayerAction.DETAIL.name());
						intent.putExtra("vgdetail",
								collectionData.get(position - 1)
										.getCacheDetailUrl());
						L.v("JasonZue",
								"详情页地址:"
										+ collectionData.get(position - 1)
												.getCacheDetailUrl());

						L.v("JasonZue",
								"time of jump to fonePlayActivity from collection:"
										+ System.currentTimeMillis());
						startActivity(intent);

						break;
					case OfflineCache.CACHE_CONTENT_TYPE_WEB_PAGE:
						// TODO 网页类的跳转事件(当前版本中暂时未出现 后续版本会添加)

						break;
					case OfflineCache.CACHE_CONTENT_TYPE_MOVIE:
					case OfflineCache.CACHE_CONTENT_TYPE_SHORT_FILM:
					case OfflineCache.CACHE_CONTENT_TYPE_NEWS:
					case OfflineCache.CACHE_CONTENT_TYPE_LIVE_AUDIO:
					case OfflineCache.CACHE_CONTENT_TYPE_LIVE_VIDEO:
					case OfflineCache.CACHE_CONTENT_TYPE_ORIGINAL:
						// 直接播放类的跳转事件
						// 如果下载状态为完成,将本地文件地址丢过去播放

						Intent intent1 = new Intent(mContext,
								FonePlayerActivity.class);

						intent1.putExtra("from", PlayerFrom.COLLECTION_LIST);
						intent1.putExtra("action", PlayerAction.DETAIL.name());
						intent1.putExtra("vgdetail",
								collectionData.get(position - 1)
										.getCacheDetailUrl());
						L.v("JasonZue",
								"详情页地址:"
										+ collectionData.get(position - 1)
												.getCacheDetailUrl());

						L.v("JasonZue",
								"time of jump to fonePlayActivity from collection:"
										+ System.currentTimeMillis());
						startActivity(intent1);
						break;
					}

					break;
				case MANAGEMENT_MODE:
					// 收藏管理模式
					collectionData.get(position - 1).setCacheIsDelete(
							!collectionData.get(position - 1)
									.getCacheIsDelete());
					mBox.setChecked(collectionData.get(position - 1)
							.getCacheIsDelete());
					count = 0;
					for (int i = 0; i < collectionData.size(); i++) {
						if (collectionData.get(i).getCacheIsDelete()) {
							collectionData
									.get(i)
									.setCacheSynchronzieType(
											OfflineCache.CACHE_FAVOURITE_SYNCHRONZIE_DELETE_WAIT);
							count++;
						}

					}

					if (count == 0) {
						deleteBt.setText(mContext.getResources().getString(
								R.string.collection_title_right_delete_text));
						deleteBt.setTextColor(mContext.getResources().getColor(
								R.color.btn_unpress_text_color));
					} else {
						deleteBt.setText("删除(" + count + ")");
						deleteBt.setTextColor(mContext.getResources().getColor(
								R.color.btn_pressed_text_color));
					}

					if (collectionData.size() == count) {
						selectAll.setText(mContext.getResources().getString(
								R.string.collection_cancel_all_text));
						isSelectedAllbt = true;
					} else {
						selectAll.setText(mContext.getResources().getString(
								R.string.collection_select_all_text));
						isSelectedAllbt = false;
					}
					break;
				default:
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
				L.e(TAG, "out of index", "NetCollectionOnitemClick");
			}
		}
	}

	/**
	 * 重置更新剧集收藏数量
	 * 
	 * @return void
	 * @throws
	 */
	private void resetCollectionNewCount() {
		SharedPreferences mSp = mContext.getSharedPreferences(
				FoneConstant.FONE_SP_NAME_SP, Activity.MODE_PRIVATE);
		mSp.edit().putInt(FoneConstant.COLLETION_TV_UPDATE_COUNT, 0).commit();
	}
}
